﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using T.FAS.Runtime.Action.SPI;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.Metadata.Entity.DataModel;
using T.FAS.Runtime.Metadata.Client;
using T.ServiceComponent.DataAccessEx.Core;

namespace T.FAS.Runtime.Action.Engine
{
    class ActionTransExecuteEngine : AbsActionExecuteEngine
    {
        public ActionTransExecuteEngine()
        {
            GetDefaultConfig();
        }

        public ActionTransExecuteEngine(ActionExecuteEngineConfig config)
        {
            this.config = config;
        }

        public override TResult Execute(ActionExecContext context)
        {
            var isNeedRemoteInvoke = ActionRouterManager.Instance.IsRemoteInovke(context);
            if (isNeedRemoteInvoke)
            {
                return RemoteInvoke(context);
            }
            else
            {
                var action = ActionRTPUtil.ActionMetadataValid(context.MetaData);
                var cdo = MetaDataClientService.GetInstance().GetMetaDataContent(action.RelatedMetaDataID) as CompositeDataObject;
                ActionRTPUtil.ActionMetadataRelatedCDOValid(action.Code,cdo);
                var dbConfigKey = cdo.RootCompositeNodeObject.DataObject.Database.DatabaseConfigs.FirstOrDefault(i => i.IsDefault)?.ConfigKey;
                var database = DatabaseHelper.GetDatabaseByConnectionKey(dbConfigKey);
                var trans = database.BeginTransaction();
                try
                {
                    var result = LocalInvoke(context);
                    trans.Commit();

                    return result;
                }
                catch
                {
                    trans.Rollback();
                    throw;
                }
            }
        }
    }
}
